package com.baoyouqun.controller.weixin;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baoyouqun.base.PageResponse;
import com.baoyouqun.domain.CreateCmd.DemandCommentCreateCmd;
import com.baoyouqun.domain.Query.DemandCommentQuery;
import com.baoyouqun.domain.VO.DemandCommentVO;
import com.baoyouqun.service.DemandCommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/wx/demand/comment")
@Api(tags = "需求评论管理接口")
public class WxDemandCommentController {

    @Resource
    private DemandCommentService demandCommentService;

    @PostMapping("create")
    @ApiOperation("新增评论/回复")
    public SingleResponse<DemandCommentVO> create(@Valid @RequestBody DemandCommentCreateCmd cmd) {
        // 设置当前登录用户ID
        String userId = StpUtil.getLoginIdAsString();
        cmd.setUserId(userId);
        return demandCommentService.create(cmd);
    }

    @DeleteMapping("delete")
    @ApiOperation("删除评论")
    public Response delete(String id) {
        DemandCommentVO commentVO = demandCommentService.selectById(id);
        if (Objects.isNull(commentVO)) {
            return Response.buildFailure("100401", "评论不存在");
        }
        // 验证是否为评论所有者
        String userId = StpUtil.getLoginIdAsString();
        if (!Objects.equals(commentVO.getUserId(), userId)) {
            return Response.buildFailure("100402", "无权限删除该评论");
        }
        demandCommentService.removeById(id);
        return Response.buildSuccess();
    }

    @GetMapping("getById")
    @ApiOperation("根据ID查询评论详情")
    public SingleResponse<DemandCommentVO> selectById(String id) {
        return SingleResponse.of(demandCommentService.selectById(id));
    }

    @GetMapping("page")
    @ApiOperation("查询需求的评论列表（分页）")
    public PageResponse<DemandCommentVO> page(DemandCommentQuery query) {
        if (StringUtils.isBlank(query.getDemandId())) {
            return PageResponse.buildFailure("100401", "需求ID不能为空");
        }
        IPage<DemandCommentVO> page = demandCommentService.pageVo(query);
        return PageResponse.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }
}